import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_base_study/pageview/view/image_view.dart';

/**
 * 自动轮播封装
 */
class SwiperPage extends StatefulWidget {
  double width = 0;
  double height = 0;
  List<String> list;

  SwiperPage(
      {super.key,
      this.width = double.infinity,
      this.height = 200,
      required this.list});

  @override
  State<SwiperPage> createState() => _SwiperPageState();
}

class _SwiperPageState extends State<SwiperPage> {
  List<Widget> pageList = [];
  int _currentIndex = 0;
  late PageController _pageController;
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    //数据
    for (int i = 0; i < widget.list.length; i++) {
      pageList.add(ImageViewPage(
          width: widget.width, height: widget.height, url: widget.list[i]));
    }
    //控制器
    _pageController = PageController(initialPage: 0);
    //定时器
    _timer = Timer.periodic(Duration(seconds: 3), (timer) {
      _pageController.animateToPage((_currentIndex + 1) % pageList.length,
          duration: Duration(microseconds: 200), curve: Curves.linear);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('无线轮播图，底部带小点'),
      ),
      body: Stack(
        children: [
          SizedBox(
            height: 200,
            child: PageView.builder(
              controller: _pageController,
              itemBuilder: (context, index) {
                return pageList[index % pageList.length];
              },
              onPageChanged: (index) {
                setState(() {
                  _currentIndex = index % pageList.length;
                });
              },
            ),
          ),
          Positioned(
              //设置left right =0 会占满整行
              left: 0,
              right: 0,
              bottom: 2,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: List.generate(
                  pageList.length,
                  (index) => Container(
                    width: 10,
                    height: 10,
                    //上下左右距离
                    margin: EdgeInsets.all(5),
                    decoration: BoxDecoration(
                        color:
                            _currentIndex == index ? Colors.red : Colors.white,

                        ///----------------BoxDecoration画圆的第一种方式
                        // borderRadius: BorderRadius.circular
                        ///----------------BoxDecoration画圆的第二种方式
                        shape: BoxShape.circle),
                  ),
                ).toList(),
              ))
        ],
      ),
    );
  }
}
